package classic;

/**
 * 求闭区间[1, n]中所有数字中包含的1的总个数，
 * 如n=10，则1的个数为2，因为只有1中包含1个，10中包含1个
 *
 * @author zj
 */
public class OneNum {
    public static void main(String[] args) {
        System.out.println(oneNum(100));
    }

    public static int oneNum(int n) {
        int count = 0;  //统计个数
        int factor = 1; //当前循环处于哪一个位数上（1表示个位，10表示十位。。。）
        int lower = 0; //当前位数的低位组成的数
        int current = 0;//当前位数上的数值
        int higher = 0; //当前位数的高位组成的数

        while (n / factor != 0) {
            lower = n - (n / factor) * factor;
            current = (n / factor) % 10;
            higher = n / (factor * 10);
            switch (current) {
                case 0:
                    count += higher * factor;
                    break;
                case 1:
                    count += higher * factor + lower + 1;
                    break;
                default:
                    count += (higher + 1) * factor;
                    break;
            }
            factor *= 10;
        }
        return count;
    }
}
